package com.njupt.Tree;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/5 15:54
 * @Description: 700. 二叉搜索树中的搜索
 * @Version: 1.0
 */


public class SearchBST {

    public TreeNode searchBST1(TreeNode root, int val) {


        if(root.val == val){
            return root;
        }else if(val < root.val){
            if(root.left != null){
                return searchBST1(root.left,val);
            }

        }else {
            if(root.right != null){
                return searchBST1(root.right,val);
            }
        }
        return null;
    }

    public TreeNode searchBST(TreeNode root, int val) {


       if(root == null || root.val == val){
           return root;
       }
       TreeNode result = null;
       if(val < root.val){
           result = searchBST(root.left,val);
       }
       if(val > root.val){
           result = searchBST(root.right,val);
       }
       return result;

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right =  new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);

        SearchBST test = new SearchBST();
        TreeNode treeNode = test.searchBST(root, 5);
        System.out.println();
    }
}
